using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace PluginPathFinder
{

    public class PathFollowToPositionAndSnapToGround : PathFollower
    {
        Vector3 directionOfRayCast;
        float offsetDistanceFromPoint;
        int maxDistanceForRayCast;
        LayerMask backgroundLayerMask;
        float offsetDistanceToFloatFromGround;

        public void SetContext(Vector3 directionOfRayCast, float offsetDistanceFromPoint, float offsetDistanceToFloatFromGround, int maxDistanceForRayCast, int groundLayer)
        {
            this.directionOfRayCast = directionOfRayCast.normalized;
            this.offsetDistanceFromPoint = offsetDistanceFromPoint;
            this.maxDistanceForRayCast = maxDistanceForRayCast;
            this.offsetDistanceToFloatFromGround = offsetDistanceToFloatFromGround;

            backgroundLayerMask = 1 << groundLayer;
        }

        public override void MoveTo(int pointIndex)
        {
            var targetPos = CastToVec(_pathToFollow[pointIndex]);

            var deltaPos = targetPos - _transform.position;

            _transform.up = Vector3.up;
            _transform.forward = targetPos - _transform.position;

            if (directionOfRayCast.x != 0)
                targetPos.x = _transform.position.x;
            if (directionOfRayCast.y != 0)
                targetPos.y = _transform.position.y;
            if (directionOfRayCast.z != 0)
                targetPos.z = _transform.position.z;

            var newTransformPos = Vector3.MoveTowards(_transform.position,targetPos,Time.deltaTime * moveSpeed);
            newTransformPos = AdjustPosition(newTransformPos);
            _transform.position = newTransformPos;
        }

        public override bool IsOnPoint(int pointIndex)
        {
            Vector3 finalPoint = AdjustPosition(CastToVec(_pathToFollow[pointIndex]));
            float mag = (_transform.position - finalPoint).sqrMagnitude;
            return mag < 0.1f;
        }

        private Vector3 AdjustPosition(Vector3 position)
        {
            position.y = Terrain.activeTerrain.SampleHeight(transform.position);
            return position;
        }
    }
}
